package cn.edu.buaa.treehole.controller.get;

import cn.edu.buaa.treehole.service.TimeService;
import cn.edu.buaa.treehole.dao.exception.DaoException;
import cn.edu.buaa.treehole.dao.exception.PidNotExistException;
import cn.edu.buaa.treehole.pojo.PostInfo;
import cn.edu.buaa.treehole.pojo.network.get.PostNetworkInfo;
import cn.edu.buaa.treehole.service.PostInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/*
 * @author Deng XinYu
 * */
@Controller
@RequestMapping("/post_info")
public class PostInfoController {
    PostInfoService postInfoService;
    TimeService timeService;

    @Autowired
    public PostInfoController(PostInfoService postInfoService, TimeService timeService) {
        this.postInfoService = postInfoService;
        this.timeService = timeService;
    }

    @RequestMapping("/{pid}")
    @ResponseBody
    public PostNetworkInfo getInfo(@PathVariable long pid) {
        PostNetworkInfo out = new PostNetworkInfo();
        System.out.println(Long.toString(pid));
        try {
            PostInfo info = postInfoService.getPostInfo(pid);
            out.setPid(info.getPid());
            out.setStatus(info.getContent());
            out.setTitle(info.getTitle());
            out.setContent(info.getContent());
            out.setTime(timeService.format(info.getDate()));
            out.setStatus("success");
        } catch (PidNotExistException e) {
            out.setStatus("null");
        } catch (DaoException e) {
            out.setStatus("exception");
        }
        try {
            out.setReplyNumber(postInfoService.getRepliesCount(pid));
        } catch (PidNotExistException e) {
            out.setStatus("null");
        } catch (DaoException e) {
            out.setStatus("exception");
        }

        return out;
    }
}
